package club.laowang.chain.validation;

import club.laowang.chain.annotation.Length;
import club.laowang.chain.annotation.Max;
import club.laowang.chain.annotation.Min;

import java.lang.reflect.Field;

public class Validator {
    private ValidatorContext context;

    public Validator() {
        this.context = new ValidatorContext();
    }

    public ValidatorChain buildValidatorChain(Field field) {
        ValidatorChain chain = new ValidatorChain(context);

        Max max = field.getAnnotation(Max.class);
        if (max != null) {
            chain.addLastHandler(new MaxValidatorHandler(max));
        }
        Min min = field.getAnnotation(Min.class);
        if (min != null) {
            chain.addLastHandler(new MinValidatorHandler(min));
        }
        Length length = field.getAnnotation(Length.class);
        if (length != null) {
            chain.addLastHandler(new LengthValidatorHandler(length));
        }

        return chain;
    }

    public void validate(Object bean) throws IllegalAccessException {
        // 获取bean的class对象
        Class<?> beanClass = bean.getClass();

        // 遍历class对象的所有域
        for (Field field : beanClass.getDeclaredFields()) {
            field.setAccessible(true);
            ValidatorChain chain = buildValidatorChain(field);
            chain.validate(field.get(bean));
        }
        context.throwExceptionIfNecessary();
    }
}
